<?php

class Event_ProductPostSelect extends Crud_Event_Handler
{
	protected $_type = 'postSelect';

	/**
	 * Run handler with options array.
	 *
	 * @param Db_Select $row
	 * @return void
	 */
	public function run($select)
	{
		$search = $this->_getParam('asearch', array());

		$filled = array();
		foreach ($search as $name => $value) {
			if ($value == '') continue;
			$filled[$name] = $value;
		}
		//фильтр по тегам
		if(isset($filled['tag'])){
			$tag = $filled['tag'];
			$select->join('tag2product', 'product.id = tag2product.product_id', array());
			$select->where('tag2product.tag_id = ?', $tag);
		}
		//фильтр по категориям
		if(isset($filled['category'])){
			$cat = $filled['category'];
			$select->join('product2product_category', 'product.id = product2product_category.product_id',array());
			$select->where('product2product_category.category_id = ?', $cat);
		}

		//Запросы по каждому атрибуту отдельно
		if(isset($filled['size']) || isset($filled['color']) || isset($filled['material']) || isset($filled['dimension']))
		{
			//$select->join('product2product_attribute', 'product.id = product2product_attribute.product_id', array());

			$sel = "";
			if(isset($filled['size'])){
				$value = addslashes($filled['size']);
				$sel .= "id IN (SELECT product_id FROM product2product_attribute WHERE attribute_value like '%$value%' AND attribute_id = 1)";
			}

			if(isset($filled['color'])){
			$value = addslashes($filled['color']);
				if($sel != ""){
					$sel .= " AND ";
				}
				$sel .= "id IN (SELECT product_id FROM product2product_attribute WHERE attribute_value like '%$value%' AND attribute_id = 4)";
			}

			if(isset($filled['material'])){
			$value = addslashes($filled['material']);
				if($sel != ""){
					$sel .= " AND ";
				}
				$sel .= "id IN (SELECT product_id FROM product2product_attribute WHERE attribute_value like '%$value%' AND attribute_id = 2)";
			}

			if(isset($filled['dimension'])){
			$value = addslashes($filled['dimension']);
				if($sel != ""){
					$sel .= " AND ";
				}
				$sel .= "id IN (SELECT product_id FROM product2product_attribute WHERE attribute_value like '%$value%' AND attribute_id = 3)";
			}

			$select->where($sel);
		}

		if(isset($filled['country_id'])){
			$country = $filled['country_id'];
			$select->where('`country_id` = '.$country);
		}

		if(isset($filled['age_from'])){
			if ($filled['age_from'] == "рожд") {
				$select->orWhere(' `age_from` = 0 AND `from_born` = 1');
			} else {
				$select->where(' `age_from` = '.$filled['age_from']);
			}
		}
	}
}

